/* 
* Copyright (c) 2009, The University of Texas at Austin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, 
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation and/or other materials 
* provided with the distribution.
*
* Neither the name of The University of Texas at Austin nor the names of its contributors may be 
* used to endorse or promote products derived from this software without specific prior written 
* permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System.Diagnostics;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using Bio.Views.Alignment.ViewModels;
using JulMar.Windows.UI;
using Microsoft.Windows.Controls;

namespace Bio.Views.Alignment.Views
{
    public partial class AlignmentEditor
    {
        public AlignmentEditor()
        {
            InitializeComponent();
            LayoutRoot.SizeChanged += AlignmentEditor_SizeChanged;
        }

        void AlignmentEditor_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            AlignmentViewModel viewModel = (AlignmentViewModel) DataContext;
            Debug.Assert(viewModel != null);

            // Inform the view model we've been resized
            viewModel.OnViewResized(e.NewSize);

            // Update the DG columns
            CalculateDataGridColumns();
        }

        protected override void OnPreviewMouseWheel(MouseWheelEventArgs e)
        {
            AlignmentViewModel viewModel = (AlignmentViewModel)DataContext;
            Debug.Assert(viewModel != null);

            if (e.Delta < 0)
                viewModel.ScrollLineDown();
            else
                viewModel.ScrollLineUp();

            e.Handled = true;
        }

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            AlignmentViewModel viewModel = (AlignmentViewModel)DataContext;
            Debug.Assert(viewModel != null);

            if (e.Key == Key.PageUp)
            {
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                    viewModel.ScrollPageLeft();
                else
                    viewModel.ScrollPageUp();

                e.Handled = true;
            }
            else if (e.Key == Key.PageDown)
            {
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                    viewModel.ScrollPageRight();
                else
                    viewModel.ScrollPageDown();
                e.Handled = true;
            }
            else if (e.Key == Key.Up)
            {
                if (FocusedRow == 0 || Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    viewModel.ScrollLineUp();
                    e.Handled = true;
                }
            }
            else if (e.Key == Key.Down)
            {
                if (FocusedRow == viewModel.VisibleRows-1 || Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    viewModel.ScrollLineDown();
                    e.Handled = true;
                }
            }
            else if (e.Key == Key.Left)
            {
                if (FocusedColumn <= 1 || Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    viewModel.ScrollLineLeft();
                    e.Handled = true;
                }
            }
            else if (e.Key == Key.Right)
            {
                if (FocusedColumn >= viewModel.VisibleColumns || Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    viewModel.ScrollLineRight();
                    e.Handled = true;
                }
            }
        }

        public int FocusedRow
        {
            get
            {
                DataGridRow item = (DataGridRow) dg.ItemContainerGenerator.ContainerFromItem(dg.CurrentItem);
                return item.GetIndex();
            }
        }

        public int FocusedColumn
        {
            get
            {
                return dg.CurrentCell.Column.DisplayIndex;
            }
        }

        private void CalculateDataGridColumns()
        {
            AlignmentViewModel viewModel = (AlignmentViewModel)DataContext;
            Debug.Assert(viewModel != null);

            if (dg != null)
            {
                if (dg.Columns.Count == 0)
                {
                    dg.Columns.Add(new DataGridTextColumn
                    {
                        Binding = new Binding("Header") { Mode = BindingMode.OneWay },
                        ElementStyle = (Style)dg.FindResource("TextBlockColumnStyle"),
                        Width = 200,
                        CanUserResize = true
                    });
                }

                int currentCount = dg.Columns.Count - 1;

                Debug.Assert(viewModel.Rows[0].Cells.Count >= viewModel.VisibleColumns);

                if (viewModel.VisibleColumns > currentCount)
                {
                    for (int i = currentCount; i < viewModel.VisibleColumns; i++)
                    {
                        dg.Columns.Add(new DataGridNucleotideColumn
                        {
                           CellStyle = (Style) dg.FindResource("CellNucleotideStyle"),
                           Width = 20,
                           Binding = new Binding("Cells[" + i + "]")
                        });
                    }
                }
                else if (viewModel.VisibleColumns < currentCount)
                {
                    for (int i = currentCount; i < viewModel.VisibleColumns; i--)
                        dg.Columns.RemoveAt(i);
                }
            }
        }

        private void OnVerticalScroll(object sender, ScrollEventArgs e)
        {
            AlignmentViewModel viewModel = (AlignmentViewModel)DataContext;
            Debug.Assert(viewModel != null);

            if (e.ScrollEventType == ScrollEventType.EndScroll ||
                e.ScrollEventType == ScrollEventType.LargeDecrement ||
                e.ScrollEventType == ScrollEventType.LargeIncrement ||
                e.ScrollEventType == ScrollEventType.SmallDecrement ||
                e.ScrollEventType == ScrollEventType.SmallIncrement)
            {
                using (new NotificationVisualizer().BeginWait(null,null))
                {
                    viewModel.CurrentRow = (int) e.NewValue;
                }
            }
        }

        private void OnHorizontalScroll(object sender, ScrollEventArgs e)
        {
            AlignmentViewModel viewModel = (AlignmentViewModel)DataContext;
            Debug.Assert(viewModel != null);

            if (e.ScrollEventType == ScrollEventType.EndScroll ||
                e.ScrollEventType == ScrollEventType.LargeDecrement ||
                e.ScrollEventType == ScrollEventType.LargeIncrement ||
                e.ScrollEventType == ScrollEventType.SmallDecrement ||
                e.ScrollEventType == ScrollEventType.SmallIncrement)
            {
                using (new NotificationVisualizer().BeginWait(null, null))
                {
                    viewModel.CurrentColumn = (int) e.NewValue;
                }
            }
        }
   }
}